
/********************************************************************************
 * Copyright(c) 2020-2025 VINCENT_WY All rights reserved.
 * - Filename
 * - Author  Vincent
 * - Version V1.0.0
 * - Date    2023/09/21
 * - Brief
 * - FunctionList:
 ******************************************************************************
 * History:
 *
 *
 *
 ******************************************************************************
 */
#include "FileReader.hpp"

#include <dirent.h>
#include <string.h>

#include <exception>
#include <filesystem>

#include "TimeUtil.h"

bool isFileExit(std::string const &fullString, std::string const &ending) {
  if (fullString.length() >= ending.length()) {
    return (0 == fullString.compare(fullString.length() - ending.length(),
                                    ending.length(), ending));
  } else {
    return false;
  }
}

FileReader::FileReader(const int type, const std::string &root) {
  _count = 0;
  _type = type;
  _root = root;
  DIR *pDir;
  struct dirent *ptr;
  if (!(pDir = opendir(_root.c_str()))) {
    std::cout << "Folder doesn't Exist!" << std::endl;
    return;
  }

  std::map<int, std::string> fileMap;
  while ((ptr = readdir(pDir)) != 0) {
    if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
      std::string mFileName = ptr->d_name;
      auto extStr = mFileName;
      if (mFileName.size() < 4) continue;
      std::string checkStr = extStr.substr(extStr.size() - 4);
      if ((checkStr != "jpeg") && (checkStr != "JPEG")) continue;
      FileInfo frame;
      getFrameInfo(_root, mFileName, frame);
      _fileInfoMap.insert({frame.freq, frame});
    }
  }
  closedir(pDir);
}

FileReader::~FileReader() { _fileInfoMap.clear(); }

std::map<int, FileInfo> FileReader::getFileInfoList() { return _fileInfoMap; }

void FileReader::getFrameInfo(const std::string &root, std::string name,
                              FileInfo &frame) {
  try {
    if (_type != 1) {
      sscanf(name.c_str(), "%d.jpeg", &frame.freq);
    } else {
      frame.freq = _count++;
    }
    frame.width = 1280;
    frame.height = 1280;
    frame.timestamp = TimeUtil::now_ms();
    frame.imageName = name;
    frame.fileName = root + name;
  } catch (std::exception &e) {
    std::cout << e.what() << std::endl;
  }
}
